/**
 * 保留小数位
 * @param val
 * @param num 需要保留几位小数，默认保留两位
 */
export const toFixedCustomize = (val, num = 100) => {
  if (isNaN(val)) {
    return 0;
  }
  if (val) {
    return Math.round(val * num) / num
  }
  return val;
}

/**
 * 生成Uuid
 * @returns uuid
 */
export const generateUuid = () => {
  var tempUrl = URL.createObjectURL(new Blob());
  var uuid = tempUrl.toString();
  URL.revokeObjectURL(tempUrl);
  return uuid.substr(uuid.lastIndexOf('/') + 1);
}
/**
 * 判断服务请求是否成功
 * @param response
 * @returns {*|boolean}
 */
export function isResponseSuccess (response) {
  return response && response.retStatus && response.retStatus === '1';
}

/**
 * 判断服务请求是否成功
 * @param retStatus
 * @returns {*|boolean}
 */
export function isResponseSuccessState (retStatus) {
  return retStatus === '1';
}

/* 取交集判断是否有重复的方法 */
export const judgeIsRepeatFunc = (originalList, currentList, filedType) => {
  /**
   * @originalList 原始集合
   * @currentList 当前集合
   * @filedType 比较的字段名称，如果没有，就默认比较遍历值
  */
  const originalSet = new Set(originalList);
  const currentSet = new Set(currentList);
  const intersectSet = new Set(
    [...originalSet].filter(
      item => currentSet.has(filedType ? item[filedType] : item)
    )
  );
  /* 返回交集对象（数组和其长度），如果长度不为0，则证明两个集合有重复对象或值 */
  return {
    list: [...intersectSet],
    length: intersectSet.size
  };
}

/**
 * 根据真假值获取回显文本
 * @param {* h} h
 * @param {* 真假值} val
 * @param {* 真值文本，默认为是} trueText
 * @param {* 假值文本，默认为否} falseText
 * @param {* 真值value，默认为1} trueValue
 * @param {* 假值value，默认为2} trueValue
 */
export const getEchoTextByTrueOrFalse = ({
  h, val, trueText = '是', falseText = '否',
  trueValue = '1', falseValue = '2'
}) => {
  if (!val) { return <span></span> }
  const textMappings = {
    [trueValue]: trueText,
    [falseValue]: falseText
  }
  return <span>{ textMappings[val] || '' }</span>
}

/**
 * 打开新窗口
 * @param {* this} e
 * @param {* 参数} data
 */
export const handleOpenNewPage = (e, data) => {
  const { href } = e.$router.resolve(data);
  window.open(href, '_blank');
}

/**
 * 对象数组去重
 * @param {*} objArr
 * @param {*} prop
 */
export const uniqObjInArray = (objArr, prop) => {
  return objArr.filter((item, index, self) => (self.findIndex(el => el[prop] === item[prop]) === index));
}

// 校验除零外的非值
export const isFalsityExcludeZero = (val) => {
  if (val || val === 0) { return false; }
  return true;
}

/**
 * 根据导出生成Excel
 * @param {* 生成Excel的名称} excelTitle
 * @param {* 生成Excel的内容} res
 */
export const createExcelByExport = ({ excelTitle, res }) => {
  const blob = new Blob([res], {
    type: 'application/octet-stream'
  });
  let link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  link.download = `${excelTitle}.xlsx`;
  link.click();
  window.URL.revokeObjectURL(blob); // 释放掉blob对象
}

/**
 * 根据导出生成附件
 * @param {* 生成附件的名称} title
 * @param {* 生成附件的内容} res
 * @param {* 生成附件的类型} type
 */
export const createAttachmentByExport = ({ title, res, type }) => {
  const blob = new Blob([res], {
    type: 'application/octet-stream'
  });
  let link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  link.download = `${title}.${type}`;
  link.click();
  window.URL.revokeObjectURL(blob); // 释放掉blob对象
}

/**
 * 弹出自定义confirm框 - arguments的缘故，此处不用箭头函数
 * @param {* 其余参数，包括customArgs和submitCallBack} otherArgs
 * @param {* 页面传入的this} that
 * @param {* 要在content区域展示的文本集合} list
 * @param {* confirm弹框支持的一些自定义参数} customArgs
 * @param {* 点击仍要提交的方法} submitCallBack
 */
export const popingConfirmByCustomRender = (that, list, otherArgs) => {
  const {
    customArgs = {
      showCancelButton: true,
      confirmButtonText: '仍要提交',
      cancelButtonText: '查看详情',
      closeOnClickModal: false
    },
    submitCallBack
  } = otherArgs;
  const h = that.$createElement;
  const title = '提交异常提示';
  const errHList = list.reduce((value, item) => {
    value.push(h('p', null, item));
    return value;
  }, []);
  const divStyle = 'height: 300px; overflow-y: auto;'
  const message = h('div', { style: divStyle }, errHList);
  const runTaskByBeforeClose = (instance, done) => {
    if (submitCallBack) {
      instance.confirmButtonLoading = true;
      instance.confirmButtonText = '提交中...';
      submitCallBack().then(retStatus => {
        if (retStatus) {
          done();
          instance.confirmButtonLoading = false;
        }
      });
    } else {
      done();
    }
  }
  that.$msgbox({
    title,
    message,
    ...customArgs,
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        runTaskByBeforeClose(instance, done);
      } else {
        done();
      }
    }
  }).catch(() => {});
}
/**
 * 表格排序对比方法
 * @param {* 排序属性名} propertyName
 * @param {* 排序规则} sort
 */
export const handleSortCompare = (propertyName, sort) => {
  return (obj1, obj2) => {
    var value1 = obj1[propertyName]
    var value2 = obj2[propertyName]
    if (typeof value1 === 'string' && typeof value2 === 'string') {
      const res = value1.localeCompare(value2, 'zh')
      if (sort === 'ascending') {
        return res;
      } else if (sort === 'descending') {
        return -res;
      }
    } else {
      if (value1 <= value2) {
        return sort === 'ascending' ? -1 : 1
      } else if (value1 > value2) {
        return sort === 'ascending' ? 1 : -1
      }
    }
  }
}
/**
 * 表格现值高亮
 * @param {* Objecet} row 当前行
 * @param {* string} fileName 字段名
 * @param {* string} formatVal 格式化后的现值
 */
export const generateHighlightNode = (h, row, fileName, formatVal) => {
  const oldVal = isNumStr(row[fileName]) ? parseFloat(row[fileName]) : row[fileName];
  const newVal = isNumStr(row[`${fileName}Update`]) ? parseFloat(row[`${fileName}Update`]) : row[`${fileName}Update`];
  let isDiff = oldVal != newVal;
  return <span class={ isDiff ? 'error_color' : '' }>{ formatVal || newVal}</span>
}
/**
 * 表格现值高亮
 * @param {* string} oldVal 当前行
 * @param {* string} newVal 字段名
 * @param {* string} formatVal 格式化后的现值
 */
export const generateHighlightNodeForSalePrice = (h, oldVal, newVal, formatVal) => {
  const oldValFormat = isNumStr(oldVal) ? parseFloat(oldVal) : oldVal;
  const newValFormat = isNumStr(newVal) ? parseFloat(newVal) : newVal;
  let isDiff = oldValFormat != newValFormat;
  return <span class={ isDiff ? 'error_color' : '' }>{ formatVal || newVal}</span>
}
/**
 * 判断是不是纯数字字符串
 * @param {* string} str 字符串
 */
const isNumStr = (str) => {
  if (!str) {
    return false;
  }
  if (!isNaN(Number(str))) {
    return true;
  }
  return false;
}

/**
  * 设置权限按钮id（sessionStorage）
  * @param {* string} btnName 按钮名称；默认设置查询按钮
*/
export const setAuthBtnId = (btnName = '查询') => {
  const authorityBtnsList = JSON.parse(sessionStorage.getItem('authorityBtnsList'));
  if (!authorityBtnsList) return false;
  const btnInfo = authorityBtnsList.find(item => item.btnName == btnName);
  const buttonId = btnInfo ? btnInfo.btnParamId : '';
  sessionStorage.setItem('buttonId', buttonId);
}
// 下拉列表转为对象
export const array2Obj = (arr = []) => {
  const obj = {}
  arr && arr.map(({ value, label }) => {
    obj[value] = label
  });
  return obj
}

// 根据routeName移除当前session缓存
export const removeSessionByRoute = ({ toName, notRemoveNames, cacheKey }) => {
  if (!cacheKey) return false;
  let notRemoveList = []
  if (typeof notRemoveNames === 'string') {
    notRemoveList = [notRemoveNames];
  } else {
    notRemoveList = notRemoveNames;
  }
  if (notRemoveList.includes(toName)) return false;
  sessionStorage.removeItem(cacheKey);
}
// 对象数组转对象
export const list2Obj = (list = []) => {
  const obj = {}
  if (list && list.length) {
    list.forEach(({ value, label }) => {
      obj[value] = label
    });
  }
  return obj
}
// 通过表单项生成初始值对象
export const initFormFieldsValue = (list) => {
  const obj = {}
  list.flat().forEach(({ prop, type, multiple, defaultValue }) => {
    const isMultiple = ['select'].includes(type) && multiple
    const isRange = ['datePicker'].includes(type)
    if (isRange || isMultiple) {
      obj[prop] = []
    } else if (['number', 'select'].includes(type)) {
      obj[prop] = defaultValue
    } else {
      obj[prop] = typeof defaultValue !== 'undefined' ? defaultValue : ''
    }
  });
  return obj
}
